package com.fausto.learnimprint.log.controller

import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.domain.Sort
import org.springframework.data.mongodb.core.MongoTemplate
import org.springframework.data.mongodb.core.query.Criteria
import org.springframework.data.mongodb.core.query.Query
import org.springframework.stereotype.Component
import org.springframework.util.ObjectUtils
import java.util.*

@Component
class ControllerLogDAO {
    @Autowired
    lateinit var mongoTemplate: MongoTemplate

    /**
     * 创建对象
     */
    fun saveControllerLog(log: ControllerLog) {
        mongoTemplate.save(log)
    }

    /**
     *      查找最新log
     */
    fun findNewestLog(left: Date, right: Date, size: Int): List<ControllerLog> {
        var condition = Criteria()
        if (!ObjectUtils.isEmpty(left) || !ObjectUtils.isEmpty(right)) {
            condition = condition.and("date")
            if (!ObjectUtils.isEmpty(left)) {
                condition.gt(left)
            }
            if (!ObjectUtils.isEmpty(right)) {
                condition.lte(right)
            }
        }
        val query: Query = Query(condition).limit(size)
            .with(Sort.by(Sort.Order.desc("date")))
        return mongoTemplate.find(query, ControllerLog::class.java)
    }
}